<template>
  <div class="sidebar" :class="{ 'collapsed': isCollapsed }">
    <div class="logo">
      <h1 v-if="!isCollapsed">CloudBlog <span class="ai-text">AI</span></h1>
      <h1 v-else class="logo-collapsed">
        <span class="ai-text">AI</span>
      </h1>
    </div>
    
    <div class="menu-section">
      <div class="menu-item">
        <div class="menu-icon">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="3"/>
            <path d="M12 1v6m0 6v6m11-7h-6m-6 0H1"/>
          </svg>
        </div>
        <span v-if="!isCollapsed">历史记录</span>
      </div>
    </div>
    <div class="history-list-container" v-if="!isCollapsed">
        <!-- 加载状态 -->
        <div v-if="loading" class="history-loading">
          加载中...
        </div>
        <!-- 错误状态 -->
        <div v-else-if="error" class="history-error">
          {{ error }}
        </div>
        <!-- 列表渲染 -->
        <transition-group name="history-item-fade" tag="div" class="history-list" v-else>
          <div
            v-for="session in chatHistory"
            :key="session.id"
            class="history-item"
            :class="{ 'selected': session.id === props.selectedSessionId }"
            @click="selectSession(session)"
          >
            <span class="history-character-name">{{ session.characterName }}</span>
            <span class="history-timestamp">{{ formatTime(session.createTime) }}</span>
          </div>
        </transition-group>
      </div>

    <div class="bottom-section">
      <div class="collapse-button" @click="toggleSidebar">
        <div class="collapse-icon">
          <svg v-if="!isCollapsed" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="15,18 9,12 15,6"/>
          </svg>
          <svg v-else width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="9,18 15,12 9,6"/>
          </svg>
        </div>
        <span>{{ isCollapsed ? '展开' : '收起' }}</span>
      </div>
      <div class="user-info">
        <div class="user-avatar">
          <img :src="avatarUrl" alt="User Avatar">
        </div>
        <div class="user-details" v-if="!isCollapsed">
          <div class="user-name">Fanxt_Ja</div>
          <div class="user-arrow">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6,9 12,15 18,9"/>
            </svg>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="Sidebar">
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { AppConfig } from '../services/config';

// 步骤 2: 定义头像图片的 URL
// 你可以将这个 URL 替换为你自己的图片链接，或者从本地导入
// 如果图片在 `src/assets` 目录下，可以使用 import 的方式
import userAvatar from '../assets/head1.jpg';
const avatarUrl = ref(userAvatar);

const isCollapsed = ref(false)

const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value
}

// --- 新增历史会话功能 ---

// 定义会话项的类型
interface ChatSession {
  id: string;
  characterName: string;
  modelName: string;
  createTime: string;
}

// 定义API响应的完整类型
interface ChatListResponse {
  code: number;
  message: string;
  data: {
    message: string;
    data: ChatSession[];
  };
}

// 修改点 2: 新增 props 定义，用于接收来自 App.vue 的当前会话ID
const props = defineProps<{
  selectedSessionId: string | null
}>()

const chatHistory = ref<ChatSession[]>([])
const loading = ref(false)
const error = ref('')

// --- 新增：用于追踪选中的会话 ---
// const selectedSessionId = ref<string | null>(null)

// 定义 emit，用于通知父组件会话已被选择
const emit = defineEmits(['session-selected'])

// 获取会话列表的方法
const fetchChatList = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await axios.get<ChatListResponse>(AppConfig.ai.chatUrl + '/ai/getChatList')
    if (response.data.code === 200 && response.data.data?.data) {
      chatHistory.value = response.data.data.data
    } else {
      error.value = '加载列表失败'
      console.error('获取会话列表失败:', response.data.message)
    }
  } catch (err) {
    error.value = '网络请求出错'
    console.error('请求会话列表时出错:', err)
  } finally {
    loading.value = false
  }
}

// 在组件挂载时自动获取列表
onMounted(() => {
  fetchChatList()
})

// 点击会话项时触发的事件
const selectSession = (session: ChatSession) => {
  console.log('选择的会话:', session)
  emit('session-selected', session) // 发出整个对象
}

// 格式化时间戳
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  return date.toLocaleString(); // 或者使用更复杂的格式化库如 date-fns
}

// 通过 defineExpose 将方法暴露给父组件
defineExpose({
  fetchChatList
})

</script>


<style scoped>
.sidebar {
  width: 280px;
  background-color: white;
  border-right: 1px solid #e5e5e5;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  transition: width 0.3s ease, padding 0.3s ease;
  overflow: hidden;
  position: relative;
}

.sidebar.collapsed {
  width: 60px;
  padding: 20px 10px;
}

.logo {
  margin-bottom: 40px;
  transition: all 0.3s ease;
}

.logo h1 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.logo-collapsed h1 {
  font-size: 18px;
}

.ai-text {
  color: #4285f4;
  font-weight: 700;
}

.menu-section {
  /* 移除 flex: 1 属性，避免占据过多空间导致内容居中 */
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}


.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  color: #666;
  font-size: 14px;
}

.menu-item:hover {
  background-color: #f8f9fa;
}

.menu-icon {
  margin-right: 12px;
  display: flex;
  align-items: center;
}

.bottom-section {
  margin-top: auto;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.user-info:hover {
  background-color: #f8f9fa;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  /* background-color: #f0f0f0; */
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 12px;
  color: #666;
  flex-shrink: 0; /* 防止头像被压缩 */
  overflow: hidden;
}

/* 步骤 3.2: 为头像内部的图片添加样式 */
.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 这能确保图片不变形地填充满整个容器 */
}

.user-details {
  display: flex;
  align-items: center;
  flex: 1;
}

.user-name {
  font-size: 14px;
  color: #333;
  margin-right: 8px;
}

.user-arrow {
  margin-left: auto;
  color: #999;
}

.collapse-button {
  padding: 12px 16px;
  margin-bottom: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background-color: #f8f9fa;
  border: 1px solid #f0f0f0;
}

.collapse-button:hover {
  background-color: #e9ecef;
  border-color: #e0e0e0;
  color: #495057;
}

.collapse-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 折叠状态下的样式 */
.sidebar.collapsed .collapse-button {
  justify-content: center;
}

.sidebar.collapsed .collapse-button span {
  display: none;
}

.sidebar.collapsed .collapse-icon {
  margin: 0;
}

/* 折叠状态下只显示图标，不隐藏整个菜单和用户信息 */
.sidebar.collapsed .menu-section {
  opacity: 1;
  transform: translateX(0);
  pointer-events: auto;
}

.sidebar.collapsed .user-info {
  justify-content: center;
  padding: 12px 8px;
}

/* 调整折叠状态下菜单和用户信息的布局 */
.sidebar.collapsed .menu-item {
  justify-content: center;
  padding: 12px 8px;
}

.sidebar.collapsed .menu-icon {
  margin-right: 0;
}

.sidebar.collapsed .user-avatar {
  margin-right: 0;
  width: 32px; /* 确保收起时尺寸固定 */
  height: 32px; /* 确保收起时尺寸固定 */
}

/* 确保过渡效果平滑 */
.menu-item,
.user-info,
.logo h1 {
  transition: all 0.3s ease;
}

/* 新增历史记录列表样式 */
.history-list-container {
  margin-top: 10px;
  overflow-y: auto;
  /* 移除 flex-grow: 1 属性，避免自动伸展 */
  padding-right: 5px; /* 滚动条空间 */
  max-height: calc(100vh - 200px); /* 限制最大高度，确保内容从顶部排列 */
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  padding: 10px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s ease, transform 0.2s ease;
  border: 1px solid #f0f0f0;
  border-left: 3px solid transparent; 
}

.history-item:hover {
  background-color: #e8f0fe; /* 蓝色悬浮效果 */
  transform: translateY(-1px);
}

/* --- 新增：选中状态的样式 --- */
.history-item.selected {
  background-color: #e8f0fe; /* 选中时的背景色 */
  border-color: #e8f0fe; /* 统一边框颜色 */
  border-left: 3px solid #4285f4; /* 左侧显示蓝色高亮边框 */
}

/* 优化：当一个项被选中时，hover效果可以不那么明显 */
.history-item.selected:hover {
  background-color: #e8f0fe; /* 保持选中颜色 */
  transform: translateY(0); /* 取消浮动效果 */
}

.history-character-name {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.history-timestamp {
  display: block;
  font-size: 12px;
  color: #888;
}

.history-loading, .history-error {
  text-align: center;
  color: #999;
  font-size: 14px;
  padding: 20px;
}

/* 列表项进入/离开动画 */
.history-item-fade-enter-active,
.history-item-fade-leave-active {
  transition: all 0.3s ease;
}
.history-item-fade-enter-from,
.history-item-fade-leave-to {
  opacity: 0;
  transform: translateX(-20px);
}

/* 滚动条美化 */
.history-list-container::-webkit-scrollbar {
  width: 4px;
}
.history-list-container::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 2px;
}
.history-list-container::-webkit-scrollbar-track {
  background: transparent;
}
</style>